package cn.tang.crm.config;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ServerConfigParser {
	private static Logger logger = Logger.getLogger(ServerConfigParser.class);

	private static final String DATABASE_NAME = "database-name";
	private static final String DATABASE_URL = "database-url";
	private static final String DATABASE_DRIVER = "database-driver";
	private static final String DATABASE_USERNAME = "database-username";
	private static final String DATABASE_PASSWORD = "database-password";

	private final String configFile = "configure.xml";
	private Document doc;
	private XPath path;

	public void init() throws SAXException, IOException,
			ParserConfigurationException {
		DocumentBuilder builder = DocumentBuilderFactory.newInstance()
				.newDocumentBuilder();
		doc = builder.parse(ServerConfigParser.class.getClassLoader()
				.getResourceAsStream(configFile));
		path = XPathFactory.newInstance().newXPath();
	}

	public void parse(Configure configure) {
		try {
			init();
			parseDatabaseConfig(configure);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("parse " + configFile + " error :" + e.getMessage());
			System.exit(-1);
		}
	}

	public void parseDatabaseConfig(Configure configure)
			throws XPathExpressionException {
		NodeList dbConfigNodeList = (NodeList) path.evaluate(
				"crm-configure/database-config", doc, XPathConstants.NODESET);
		if (dbConfigNodeList == null || dbConfigNodeList.getLength() != 1) {
			logger.error("db configure not find");
			System.exit(-1);
		}
		NodeList childNode=dbConfigNodeList.item(0).getChildNodes();
		for (int i = 0; i < childNode.getLength(); ++i) {
			Node dbConfigNode = childNode.item(i);
			if (dbConfigNode.getNodeName().equals(DATABASE_NAME)) {
				configure.setDbName(dbConfigNode.getTextContent());
			} else if (dbConfigNode.getNodeName().equals(DATABASE_URL)) {
				configure.setDbURL(dbConfigNode.getTextContent());
			} else if (dbConfigNode.getNodeName().equals(DATABASE_DRIVER)) {
				configure.setDbDriver(dbConfigNode.getTextContent());
			} else if (dbConfigNode.getNodeName().equals(DATABASE_USERNAME)) {
				configure.setDbUserName(dbConfigNode.getTextContent());
			} else if (dbConfigNode.getNodeName().equals(DATABASE_PASSWORD)) {
				configure.setDbPassword(dbConfigNode.getTextContent());
			}
		}
	}

}
